<?php

// Namespace

namespace Snsfg;


/**
 * CSocialNetworkAccount is a class that can be used to manage social network accounts
 *
 * @package		Snsfg
 * @category	Model
 */

class CWechat extends \Loop\CObject
{

    protected function createProperties()
    {
        parent::createProperties();

        $this->createProperty
        (
            'toUserName',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'fromUserName',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'createTime',
            array
            (
                'type' => TYPE_TIMESTAMP
            )
        );

        $this->createProperty
        (
            'msgType',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'event',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'eventKey',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'ticket',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'latitude',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'longitude',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'precision',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'content',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'msgId',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'picUrl',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'mediaId',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'format',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'thumbMediaId',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'scale',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'label',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'title',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'description',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'url',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'recognition',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'status',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'totalCount',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_SHORT
            )
        );

        $this->createProperty
        (
            'filterCount',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_SHORT
            )
        );

        $this->createProperty
        (
            'sentCount',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_SHORT
            )
        );

        $this->createProperty
        (
            'errorCount',
            array
            (
                'isName' => true,
                'type' => TYPE_STRING_SHORT
            )
        );

        $this->createProperty
        (
            'unknown',
            array
            (
                'isName' => true,
                'type' => TYPE_TEXT_SHORT
            )
        );

        $this->createProperty
        (
            'efId',
            array
            (
                'type' => TYPE_STRING_LONG
            )
        );

        $this->createProperty
        (
            'universe',
            array
            (
                'type' => TYPE_STRING_SHORT
            )
        );

    }


    public function api_getResponse()
    {
        $msgId = fv('msgId', true);
        $rawMessage = $this->find
        (
            array
            (
                'properties' => array('toUserName','fromUserName','createTime','msgType','event','msgId','status','totalCount','filterCount','sentCount','errorCount','content'),
                'conditions' => array
                (
                    'msgId' => array(EQUAL, $msgId)
                ),
                'orderBy' => array('timeOfCreation'),
                'orderDirection' => 'ascendent'
            )
        );

        if (count($rawMessage) == 1)
        {
         echo json_encode(array_shift($rawMessage));
        }
        else
        {
            echo json_encode(array(
                    'msgId' => $msgId,
                    'error' => 'Not found'
                ));
        }

        exit;

    }


	public function api_response()
	{

        $efId = fv('ef_user_id');
        $universe = fv('ef_universe_id');
        $echostr = fv('echostr');

		if (!isset($echostr)) {

/*
            $rawResponses = $this->find
            (
                array
                (
                    'conditions' => array
                    (
                        'universe' => array(EQUAL, $universe)
                    )
                )
            );
var_dump($rawResponses);die;
            if (count($rawResponses) == 1)
            {
                $this->reset();
                $this->loadFromRawObject(array_shift($rawResponses));
            }
*/

            $this->setEfId($efId);
            $this->setUniverse($universe);

		    $this->responseMsg();
		}else{
		    $this->valid();
		}
	}


	private function checkSignature()
    {
        $signature = fv('signature');
        $timestamp = fv('timestamp');
        $nonce = fv('nonce');

        $token = substr(md5(date('Ymd')), 7, 8);

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }


    /**
     *
     */

    public function getResponse($msgId)
    {
        $result = array();

        $rawMessage = $this->find
        (
            array
            (
                'properties' => array('toUserName','fromUserName','createTime','msgType','event','msgId','status','totalCount','filterCount','sentCount','errorCount','content'),
                'conditions' => array
                (
                    'msgId' => array(EQUAL, $msgId)
                ),
                'orderBy' => array('timeOfCreation'),
                'orderDirection' => 'ascendent'
            )
        );

        if (count($rawMessage) == 1)
        {
         $result = array_shift($rawMessage);
        }
        else
        {
            $result = array(
                    'msgId' => $msgId,
                    'error' => 'Not found'
                );
        }

        return $result;
    }


    // Receive event
    public function receiveEvent($object)
    {

        $this->setToUserName($object->ToUserName);
        $this->setFromUserName($object->FromUserName);
        $this->setCreateTime($object->CreateTime);
        $this->setMsgType($object->MsgType);
        $this->setEvent($object->Event);


        $content = "";
        switch (strtolower($object->Event))
        {
            case "subscribe":
                break;
            case "unsubscribe":
                break;
            case "scan":
                $this->setTicket($object->Ticket);
                break;
            case "click":
                $this->setEventKey($object->EventKey);
                break;
            case "location":
                $this->setLatitude($object->Latitude);
                $this->setLongitude($object->Longitude);
                $this->setPrecision($object->Precision);
                break;
            case "view":
                $this->setEventKey($object->EventKey);
                break;
            case "masssendjobfinish":
                $this->setMsgId($object->MsgID);
                $this->setStatus($object->Status);
                $this->setTotalCount($object->TotalCount);
                $this->setFilterCount($object->FilterCount);
                $this->setSentCount($object->SentCount);
                $this->setErrorCount($object->ErrorCount);
                break;
            default:
                $content = "Received a new event: ".$object->Event;
                break;
        }

        $this->save();

    }
    

	public function responseMsg()
    {
        // Get POST data.
        $postStr = file_get_contents('php://input');
$this->logger('In responseMsg:'.$postStr);
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $messageType = trim($postObj->MsgType);

            // Message Types
            switch ($messageType)
            {
                case "event":
                $this->receiveEvent($postObj);
                break;
                /*
                case "text":
                $this->receiveText($postObj);
                break;
                case "image":
                $this->receiveImage($postObj);
                break;
                case "location":
                $this->receiveLocation($postObj);
                break;
                case "voice":
                $this->receiveVoice($postObj);
                break;
                case "video":
                $this->receiveVideo($postObj);
                break;
                case "link":
                $this->receiveLink($postObj);
                break;
                */
                default:
                
                break;
            }
        }
    }

    

    public function api_uploadNews()
    {
        $payload = json_decode(fv('payload', true));

        require_once(PATH_APPLICATION . 'Class/CWechatDriver.php');

        $className = __NAMESPACE__.'\\CWechatDriver';

        $wechatDriver = new $className();

        $mpnews = $wechatDriver->uploadNews($payload);

    }


    public function valid()
    {
        $echoStr = fv('echostr');
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }


    public function logger($log_content)
    {
        $max_size = 1000000;
        $log_filename = "Temporary/response.txt";
        
        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){
            unlink($log_filename);
        }

        file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    }
}